<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #chanListSelect="{ model, field }">
        <n-select v-model:value="model[field]" clearable :options="chanOptions"/>
      </template>
    </BasicForm>
    <BasicTable
      :loading="dataLoading"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="2200"
    >
      <template #toolbar>
        <n-space>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
  <basicModal style="width: 30%" @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
    <template #default>
       <BasicForm @register="editRegister" class="basicForm">
      </BasicForm>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import {computed, h, onMounted, reactive, ref, unref} from 'vue';
  import {useDialog, useMessage} from 'naive-ui';
  import {BasicTable, TableAction} from '@/components/Table';
  import {BasicForm, FormSchema, useForm} from '@/components/Form/index';
  import {getTableList} from '@/api/table/list';
  import {editCloumns, columns} from './columns';
  import {PlusOutlined, EditOutlined,AlertOutlined, DeleteOutlined} from '@vicons/antd';
  import {useModal} from "@/components/Modal";
  import {formatToDateTime} from "@/utils/dateUtil"
  import {getChanList} from "@/api/game/chan";
  import {deleteAnchor, getAnchorFilter, registerAnchor, updateAnchor} from "@/api/liveBroadcast/anchorManage";
  import {useUserStore} from "@/store/modules/user";
  import {getRedpacketPlayerPageList, updateRedpacket,openReciveRedPack} from "@/api/redpacket/redpacket";

  const chanOptions = ref([]);
  const dataLoading = ref(false);
  const schemas: FormSchema[] = [
    {
      field: 'userId',
      label: "玩家id",
      component: "NInput",
      componentProps: {
        placeholder: "请输入玩家ID进行查询",
      }
    }
  ];


  const formRef: any = ref(null);
  const message = useMessage();
  const userStore = useUserStore();
  const isDelete = userStore.getRoleType == "admin" || userStore.getRoleType == "super";
  const dialog = useDialog();
  const actionRef = ref();
  const checkedRowKes = ref([]);
  const tableDataSource = ref([]);
  const showModal = ref(false);
  const isEdit = ref(false);
  const formParams = reactive({
    userId: 0
  });
  const updateEntity = ref({});


  const actionColumn = reactive({
    width: 200,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEditRedpacket.bind(null, record),
            type: 'info',
            icon: EditOutlined,
            ifShow: () => {
              return true;
            },
          },
          {
            label: '开启',
            onClick: handleOpenRedpacket.bind(null, record),
            type: 'error',
            icon: AlertOutlined,
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: {cols: '1 s:1 m:2 l:3 xl:4 2xl:4'},
    labelWidth: 120,
    schemas,
  });

  const [modalRegister, {openModal, closeModal, setSubLoading, setProps}] = useModal({
    title: '编辑',
  });

  const loadDataTable = async (res) => {
    const param = {...formParams, ...res};
    if (!param.userId) {
      param.userId = 0
    }else {
      param.userId = parseInt(param.userId)
    }
    console.log(param);
    return await getRedpacketPlayerPageList(param);
  };


  const [editRegister, {submit: addSubmit, setFieldsValue: addSetFieldsValue}] = useForm({
    gridProps: {cols: 1},
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: editCloumns
  });


  async function okModal() {
    let formValue;
    try {
      formValue = await addSubmit();
    } catch (e) {
      message.error("请填写完整信息");
      return
    } finally {
      setSubLoading(false)
    }
    try {
      let value: any = Object.assign({}, formValue);
      value.wealth_money = Number( parseFloat(value.wealth_money).toFixed(2))
      value.newcomer_money = Number( parseFloat(value.newcomer_money).toFixed(2))
      value.lv_money = Number( parseFloat(value.lv_money).toFixed(2))
      value.live_money = Number( parseFloat(value.live_money).toFixed(2))
      value = Object.assign({}, unref(updateEntity), value);

      await updateRedpacket(value);
      message.success("编辑成功");
      closeModal()
    } finally {
      setSubLoading(false)
    }

    await reloadTable()
  }


  async function reloadTable() {
    try {
      dataLoading.value = true;
      actionRef.value.reload();
    } finally {
      dataLoading.value = false;
    }

  }

  function onCheckedRow(rowKeys: any[]) {
    checkedRowKes.value = rowKeys;
  }


  async function handleEditRedpacket(record: Recordable) {
    isEdit.value = true;
    await openModal();
    setProps({title: "编辑"});
    updateEntity.value = record;
    let obj = Object.assign({}, unref(record), {remainMoney: unref(record).remainMoney + ""});
    await addSetFieldsValue(obj)
  }
  async function handleOpenRedpacket(record: Recordable) {
    console.log("record.id==",record.id);
    dialog.info({
      title: '提示',
      content: '您确定开启所有等级红包和高级红包吗?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await openReciveRedPack({id:record.id});
        message.success('开启成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    Object.assign(unref(formParams), unref(values));
    reloadTable();
  }

  function handleReset(values: Recordable) {

    reloadTable()
  }

  onMounted(async () => {
    /*
    const chanList = await getChanList();
    chanOptions.value = chanList.map((chan) => {
      return {
        label: chan.chanName,
        value: chan.chanId
      }
    });
    */
  });
</script>

<style lang="less" scoped></style>
